package com.zhuiYun.project.config.loginhandler;

import com.zhuiYun.project.api.sysUser.entiy.SysUser;
import com.zhuiYun.project.common.errorCode.EmErrorCode;
import com.zhuiYun.project.common.response.CommonResult;
import com.zhuiYun.project.common.response.ResponseUtil;
import com.zhuiYun.project.config.jwt.JWTUtils;
import com.zhuiYun.project.util.ObjectUtils;
import com.zhuiYun.project.util.RedisUtil;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName CustomizeLogoutSuccessHandler
 * @Description 登出处理
 * @Author zcy
 * @Date 2023/3/27 11:43
 **/
@Component
public class CustomizeLogoutSuccessHandler implements LogoutSuccessHandler {

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 清空 token 和redis
        String token = JWTUtils.getToken(request);
        // 判断并清空redis中token的信息
        if(ObjectUtils.isNotEmpty(token)){
            SysUser sysUser = (SysUser)RedisUtil.get(token);
            RedisUtil.del(token);
            RedisUtil.del(sysUser.getLoginName());
        }
        SecurityContextHolder.clearContext();
        ResponseUtil.responseJson(response, CommonResult.ok(EmErrorCode.LOGIN_OUT));
    }
}
